<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <template #header>{{titleTop}}</template>
        <!-- form表单 -->
        <el-form
          ref="editForm"
          class="edit-form"
          label-width="100px"
          :model="questionsList"
          :rules="rules"
        >
          <!-- 学科 -->
          <el-form-item
            label="学科："
            prop="subjectID"
          >
            <el-select
              @change="subjectChange"
              v-model="questionsList.subjectID"
              size="medium"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item,index) in subjectName"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item
            label="目录："
            prop="catalogID"
          >
            <el-select
              v-model="questionsList.catalogID"
              size="medium"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item,index) in catalogName"
                :key="index"
                :value="item.value"
                :label="item.label"
              >

              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item
            label="企业："
            prop="enterpriseID"
          >
            <el-select
              v-model="questionsList.enterpriseID"
              size="medium"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item,index) in EnterpriseID"
                :key="index"
                :value="item.id"
                :label="item.company"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item>
            <el-row>
              <el-col style="width:198px;margin-right:4px">
                <el-form-item
                  style="margin-left:-100px"
                  label="城市："
                  prop="province"
                >
                  <el-select
                    @change="provinceChange"
                    v-model="questionsList.province"
                    size="medium"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item,index) in provs"
                      :key="index"
                      :value="item"
                      :label="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col style="width:198px">
                <el-form-item prop="city">
                  <el-select
                    v-model="questionsList.city"
                    size="medium"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in citys"
                      :key="item"
                      :value="item"
                      :label="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item
            label="方向："
            prop="direction"
          >
            <el-select
              v-model="questionsList.direction"
              size="medium"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item,index) in direction"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item
            label="题型："
            prop="questionType"
          >
            <el-radio-group v-model="questionsList.questionType">
              <el-radio
                label="1"
                @click="isRadioChange"
              >单选</el-radio>
              <el-radio
                label="2"
                @click="isRadioChange"
              >多选</el-radio>
              <el-radio
                label="3"
                @click="isRadioChange"
              >简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item
            label="难度："
            prop="difficulty"
          >
            <el-radio-group v-model="questionsList.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 富文本-->
          <el-form-item
            label="题干："
            prop="question"
          >
            <quill-editor
              style="height:200px; margin-bottom: 50px;"
              ref="myQuillEditor"
              :options="editorOption"
              v-model="questionsList.question"
            />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            :hidden="questionsList.questionType ==='3'"
          >
            <el-row
              type="flex"
              align="middle"
              v-for="(item,index) in questionsList.options"
              :key="item.code"
            >
              <!-- 单选-单选框 -->
              <el-radio
                v-if="questionsList.questionType === '1'"
                v-model="radioChecked"
                :label="item.code"
                @input="radioChange"
              >{{ item.code }}</el-radio>
              <!-- 多选框 -->
              <el-checkbox
                v-else-if="questionsList.questionType === '2'"
                v-model="item.isRight"
              >{{ item.code }}:</el-checkbox>
              <!-- 单选-input -->
              <el-input
                v-model="item.title"
                style="width: 240px; margin: 0 20px"
              ></el-input>
              <!-- 单选-上传图片 -->
              <el-upload
                v-model="item.img"
                action="#"
                :show-file-list="false"
              >
                <img
                  v-if="item.img"
                  :src="item.img"
                  style="width:101px;height:61px"
                />
                <span v-else>上传图片</span>
                <i
                  style="fontsize: 20px; position: absolute; top: 20px"
                  @click.stop="del(index)"
                ></i>
              </el-upload>
            </el-row>
          </el-form-item>
          <!-- 按钮 -->
          <el-form-item>
            <el-row>
              <el-button
                @click="addOptionsBtn"
                :disabled="questionsList.questionType==='1'"
                size="small"
                type="danger"
              >+ 增加选项与答案</el-button>
            </el-row>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item
            label="解析视频："
            prop="videoURL"
          >
            <el-input
              v-model="questionsList.videoURL"
              style="width:400px"
            ></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item
            label="答案解析："
            prop="answer"
          >
            <quill-editor
              style="height: 200px; margin-bottom: 50px"
              v-model="questionsList.answer"
              ref="myQuillEditor"
              :options="editorOption"
            >
            </quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item
            label="题目备注："
            prop="remarks"
          >
            <el-input
              type="textarea"
              :rows="4"
              v-model="questionsList.remarks"
            ></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item
            label="试题标签："
            prop="tags"
          >
            <el-select
              multiple
              filterable
              allow-create
              default-first-option
              v-model="questionsList.tags"
              placeholder="请选择"
              style="width:400px"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 确认 -->
          <el-form-item>
            <el-button
              type="primary"
              :style="submitStyle"
              @click="onSubmit"
            >{{submitBtn}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 实现代码高亮的两个文件
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
// 获取学科
import { simple as subjects } from '@/api/hmmm/subjects.js'
// 获取目录
import { simple as simples } from '@/api/hmmm/directorys.js'
// 获取试题标签
import { simple as tags } from '@/api/hmmm/tags.js'
// 获取企业
import { list as companys } from '@/api/hmmm/companys.js'
// 获取城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 获取方向
import { direction } from '@/api/hmmm/constants.js'
// 获取添加API
import { add, detail as details } from '@/api/hmmm/questions.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 上传图片、上传链接
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        placeholder: ''
      },
      radioChecked: '',
      // 校验规则：不能为空
      rules: {
        // 学科
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        // 目录
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        // 企业
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        // 城市
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        // 城市下拉地区
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        // 方向
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        // 题型
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        // 难度
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        // 题干 富文本
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        // 答案解析
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      // 接收单选框传值(互斥)
      CODE: '',
      // 题库列表
      questionsList: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 城市下拉地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干 富文本
        options: [
          // 选项
          { title: '', code: String.fromCharCode(65), img: '', isRight: false },
          { title: '', code: String.fromCharCode(66), img: '', isRight: false },
          { title: '', code: String.fromCharCode(67), img: '', isRight: false },
          { title: '', code: String.fromCharCode(68), img: '', isRight: false }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      subjectName: [], // 获取的学科列表
      EnterpriseID: [], // 获取的企业列表
      catalogName: [], // 用于显示目录的名字
      provs: [], // 获取的城市列表
      tagsList: [], // 试题标签
      citys: [], // 地区
      questionType: '1', // 题型
      count: ''
    }
  },
  watch: {
    'questionsList.questionType' () {
      this.radioChecked = ''
    }
  },
  created () {
    // 获取学科列表
    this.getSubjectList()
    // 获取企业列表
    this.getCompanysList()
    // 获取城市列表
    this.getCitysList()
    // 获取方向列表
    this.getDirectionList()
    // 获取详情数据
    if (this.$route.query.id) {
      this.getDetailList()
    }
  },
  computed: {
    // 判断标题
    titleTop () {
      return this.$route.query.id ? '试题编辑' : '试题录入'
    },
    // 判断提交修改
    submitBtn () {
      return this.$route.query.id ? '确认修改' : '确认提交'
    },
    // 判断提交修改样式
    submitStyle () {
      return this.$route.query.id ? 'marginleft: 80px;background-color:#67c23a;border-color:#67c23a;' : 'marginleft:80px'
    }
  },
  methods: {
    // 单选项发生变化的时候，让当前选中的为true
    radioChange (val) {
      // console.log(val)
      this.questionsList.options.forEach(item => {
        item.code === val ? item.isRight = true : item.isRight = false
      })
    },
    // 增加选项按钮
    addOptionsBtn () {
      this.questionsList.options.push({
        title: '',
        code: String.fromCharCode(this.questionsList.options.length + 65),
        img: '',
        isRight: false
      })
    },
    // 获取学科列表
    async getSubjectList () {
      const { data } = await subjects()
      // console.log('学科：', data)
      this.subjectName = data
    },
    // 获取企业列表
    async getCompanysList () {
      const { data: { items } } = await companys()
      // console.log('企业：', items)
      this.EnterpriseID = items
    },
    // 获取城市列表
    getCitysList () {
      this.provs = provinces()
      // console.log('城市', this.provs)
    },
    // 获取方向列表
    getDirectionList () {
      this.direction = direction
      // console.log('方向：', this.direction)
    },
    // 一级学科改变==>目录需要改变
    async subjectChange (val) {
      const { data } = await simples({ subjectID: val })
      // console.log('目录：', res)
      this.catalogName = data
      this.questionsList.catalogID = ''
      // 一级学科改变==>试题标签需要改变
      const res = await tags({ subjectID: val })
      // console.log('试题标签', res.data)
      this.tagsList = res.data
      // console.log(this.tagsList)
    },
    // 城市发生变化==》地区需要改变
    async provinceChange (val) {
      this.questionsList.city = ''
      this.citys = citys(val)
      // console.log(this.citys)
    },
    // 上传图片
    upload () { },
    // 点击确认提交验证表单发请求
    onSubmit () {
      this.$refs.editForm.validate(async (valid) => {
        // 验证不成功，返回
        // if (!valid) return
        // 验证成功，发请求-提示成功-跳页面
        if (valid) {
          // console.log(this.questionsList.tags)
          // console.log(this.questionsList.tags instanceof Array)
          // console.log(this.questionsList.tags instanceof Object)
          this.questionsList.tags = this.questionsList.tags ? this.questionsList.tags.join(',') : ''
          // console.log(this.questionsList.tags)
          await add({ ...this.questionsList, tags: this.questionsList.tags })
            .then(res => {
              this.$message.success('添加试题成功')
              // this.$router.push('/questions/list')
              this.$router.go(-1)
            })
            .catch(err => {
              this.$message.error('添加失败')
              console.log(err)
            })
          // console.log(this.questionsList)
        }
      })
    },
    // 编辑
    async getDetailList () {
      const { data: baseDataList } = await details({ id: this.$route.query.id })
      // 1. 将获取的数据 绑定表单
      this.questionsList = baseDataList
      const { data } = await simples({ subjectID: this.questionsList.subjectID })
      this.catalogName = data
      // 2. 转化标签
      this.questionsList.tags = baseDataList.tags ? baseDataList.tags.split(',') : ''
      // 3. 判断 选项的单选还是多选
      const isRightsArr = baseDataList.options.filter(item => item.isRight)
      if (isRightsArr.length > 1) {
        baseDataList.options.forEach(item => {
          item.isRight = !!item.isRight
        })
      } else {
        // console.log(isRightsArr)
        isRightsArr.forEach(item => { this.radioChecked = item.code })
      }
    },
    // 点击改变单选或多选
    isRadioChange () {
      if (this.questionsList.questionType === '1') {
        this.questionsList.options.forEach(item => {
          item.isRight = false
        })
        this.disabled = true
      } else if (this.questionsList.questionType === '2') {
        this.CODE = ''
        this.disabled = false
      }
    }
  }
}
</script>

<style scoped lang="css">
.edit-form {
  padding-left: 20px;
}
div /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.button-tag {
  margin-left: 100px;
  margin-bottom: 20px;
}
</style>
